package com.zhiwang.planet.mvvm.viewmodel.loginv2

import android.annotation.SuppressLint
import android.content.Context
import android.net.wifi.WifiManager
import android.os.Build
import android.text.Editable
import android.view.inputmethod.InputMethodManager
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.ObservableBoolean
import androidx.lifecycle.MutableLiveData
import com.tencent.bugly.crashreport.CrashReport
import com.zhiwang.planet.BuildConfig
import com.zhiwang.planet.aop.net.NetWorkRequired
import com.zhiwang.planet.aop.net.SimCardRequired
import com.zhiwang.planet.event.LoginEvent
import com.zhiwang.planet.mvvm.model.AppDataBase
import com.zhiwang.planet.mvvm.model.entity.main.WxBindBody
import com.zhiwang.planet.mvvm.model.request.LoginRequest
import com.zhiwang.planet.mvvm.model.request.SmsCodeRequest
import com.zhiwang.planet.mvvm.model.request.SmsReq
import com.zhiwang.planet.ui.WebViewActivity
import com.zhiwang.planet.ui.loginv2.LoginFillSmsActivity
import com.zhiwang.planet.util.*
import io.reactivex.functions.Action
import io.reactivex.functions.Consumer
import org.greenrobot.eventbus.EventBus

class WxLoginViewModel : RegisterViewModel() {

    val qq = MutableLiveData<String>()


    var wxCode = ""

    val bindMode = ObservableBoolean(false)

    var imei: String = ""


    var phone = MutableLiveData<String>()

    fun service() {

        WebViewActivity.load(context, Store.Service)
    }

    @SimCardRequired
    fun doWxAction() {
        wxLogin()
    }


    @NetWorkRequired
    private fun wxLogin() {
        if (agree.value == true) {
            LoginUtil.wxLogin(context)
        } else Toaster.message("未同意服务协议与隐私协议")
    }

    fun setWxLoginCode(code: String, token: String) {

        if (bindMode.get())
            bindWxAndLogin(code, token)
        else loginByWeiXin(code)

    }

    private fun loginByWeiXin(code: String) {

        val req = buildLoginReq()

        req.code = code

        restApi.wxLogin(req)
                .arrange(Consumer {

                    success = true
                    AppUtil.handleLogin(it)
                    context.suicideAfterTransition()

                }, Consumer {

                    errHandler(it)

                }, Action {

                })
    }

    private fun buildLoginReq(): LoginRequest {

        val wifiManager = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager

        var wifiName = wifiManager.connectionInfo?.ssid ?: ""

        if (wifiName.indexOf("\"") == 0 && wifiName.lastIndexOf("\"") == wifiName.lastIndex)
            wifiName = wifiName.substring(1, wifiName.lastIndex)

        return LoginRequest(
                phone = username.value ?: "",
                sms = smsCode.value ?: "",
                imei = imei,
                get_token = 1,
                androidVersion = Build.VERSION.RELEASE,
                appVersionName = BuildConfig.VERSION_NAME,
                wifiName = wifiName,
                deviceModel = Build.MODEL)
    }


    var success = false

    private fun bindWxAndLogin(code: String, token: String) {

        TokenManager.saveToken(token)
        restApi.bindWx(WxBindBody(code, token).apply { addExtra(buildLoginReq()) })
                .arrange(Consumer {

                    success = true
                    TokenManager.saveToken(it)
                    EventBus.getDefault().post(LoginEvent())
                    context.suicideAfterTransition()

                }) {
                    errHandler(it)
                }
    }


    fun start() {

//        restApi.getQQ()
//                .arrange(Consumer {
//
//                    qq.value = it.qq
//                }) {
//
//                }
    }


    fun copyQQ() {

        qq.value?.apply {
            context.copy(this)
            Toaster.message("已复制客服QQ到剪切板")
        }
    }

    fun copyDeviceId() {
        imei.apply {
            context.copy(this)
            Toaster.message("已复制设备码到剪切板")
        }
    }


    /**
     * 登录或者注册的短信号
     */
    @SuppressLint("CheckResult")
    fun getSmsRegOrLogin() {
        if(agree.value!!.not()){
            Toaster.message("请先同意用户协议")
            return
        }
        val req = SmsReq(phone.value!!)
        req.setTypeLoginReg()

        restApi.getSms(req)
                .androidSchedule()
                .responseVoidFunc()
                .subscribe({

                }, {
                    errHandler(it)

                }, {
                    context.quickStartActivity(LoginFillSmsActivity::class.java) { intent ->
                        intent.putExtra("phone", phone.value!!)
                    }
                    context.suicideAfterTransition()
                })

    }

    @SuppressLint("CheckResult")
    fun repeatGetSmsRegOrLogin() {

        val req = SmsReq(username.value!!)
        req.setTypeLoginReg()

        restApi.getSms(req)
                .androidSchedule()
                .responseVoidFunc()
                .subscribe({

                }, {
                    errHandler(it)

                }, {
                    Toaster.message("验证码已发送")
                })
    }

    var flag = false

    fun onSmsTextChange(editable: Editable) {

        val sms = editable.toString()

        if (sms.length == 6 && flag.not()) {
            smsCode.value = sms
            val req = buildLoginReq()
            restApi.loginV2(req)
                    .arrange(Consumer { token ->
                        flag = true
                        context.closeImei()
                        TokenManager.saveToken(token)
                        EventBus.getDefault().post(LoginEvent())
                        context.suicideAfterTransition()
                    }, Consumer {
                        errHandler(it)
                    }, Action {

                    })
        }

    }

}

private fun AppCompatActivity.closeImei() {

    val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(window.decorView.windowToken, 0)

}
